package com.company.array;

import java.util.Arrays;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/binary-search/
 * @date 2019/11/25 16:46
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 *               0 1 2 3 4 5
 *               2
 *               3 5
 *               4
 * 输入: nums = [-1,0,3,5,9,12], target = 9
 * 输出: 4
 * 解释: 9 出现在 nums 中并且下标为 4
 */
public class BinarySearch {

    public static void main(String[] args) {
        System.out.println(search(new int[]{-1, 0, 3, 5, 9, 12}, 9));
    }

    public static int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int mid = (left + right)/2;
        while (nums[mid] != target) {
            if (nums[mid] < target) {
                mid = (left + mid - 1) /2;
            } else {
                mid = (mid + right + 1) /2;
            }
        }
        return mid;
    }

}
